package com.rzjm.exercise.module.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.config.ProjectUrlConfig;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.FileUtil;
import com.rzjm.exercise.common.utils.OssUtil;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.module.domain.Article;
import com.rzjm.exercise.module.domain.Shop;
import com.rzjm.exercise.module.domain.Towns;
import com.rzjm.exercise.module.service.ArticleService;
import com.rzjm.exercise.module.service.ShopService;
import com.rzjm.exercise.module.service.TownsService;
import com.rzjm.exercise.sys.core.dict.domain.DictDO;
import com.rzjm.exercise.sys.core.dict.service.DictService;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping(value = "/module/article",produces ="application/json;charset=UTF-8")
public class ArticleController extends BaseController {
    @Resource
    private ArticleService articleService;
    @Resource
    private DictService dictService;
    @Resource
    private TownsService townsService;
    @Resource
    private ShopService shopService;
    @Resource
    private ProjectUrlConfig projectUrlConfig;

    @Value("${projecturl.imgurl}")
    private String imgurl;
    @Log("查询规章制度页面")
    @GetMapping("")
    @RequiresPermissions("module:article:article")
    String article(Model model) {
        UserDO user = getUser();
        QueryWrapper<Towns> qwTown = new QueryWrapper<>();
        qwTown.eq("parent_id", 0);
        qwTown.eq("district_id", 1319);
        List<Towns> townsList = townsService.list(qwTown);
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("state", 1);
        wrapper.ne("shop_type", 3);
        if (user.getTownId() != null && user.getTownId() > 0) {
            wrapper.eq("town_id", user.getTownId());
        }
        List<Shop> shopList = shopService.list(wrapper);
        model.addAttribute("townsList", townsList);
        model.addAttribute("shopList", shopList);
        model.addAttribute("user", user);
        return "module/article/list";
    }

    @Log("查询规章制度页面")
    @ResponseBody
    @GetMapping("/list")
    public DataTableLayUI<Article> list(DataTableLayUI<Article> condition) {
        DataTableLayUI<Article> dt = articleService.getListPage(condition);
        List<Article> list = dt.getData();
        list.forEach(article ->{
            article.setPreviewImg( imgurl + article.getPreviewImg());
        });
        return dt;
    }


    @Log("新增规章制度页面")
    @GetMapping("/add")
    @RequiresPermissions("module:article:add")
    String add(Model model) {
        List<DictDO> newsTypeList = dictService.listByType("news_type");
        model.addAttribute("newsTypeList", newsTypeList);
        Article article = new Article();
        model.addAttribute("article", article);
        return "module/article/detail";
    }

    @Log("编辑规章制度页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:article:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        Article article = articleService.findById(id);
        model.addAttribute("article", article);
        List<DictDO> newsTypeList = dictService.listByType("news_type");
        model.addAttribute("newsTypeList", newsTypeList);
        return "module/article/detail";
    }


    /**
     * 保存
     */
    @Log("新增规章制度")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:article:add")
    public R save(@Valid Article article) {
        UserDO user = getUser();
        article.setCreateTime(new Date());
        article.setArticleType(0);
        article.setState(1);
        article.setCompanyId(user.getShopId());
        articleService.save(article);
        return R.ok();
    }



    /**
     * 修改
     */
    @Log("更新规章制度")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:article:edit")
    public R update(@Valid Article article) {
        articleService.updateById(article);
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除规章制度")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("module:article:remove")
    public R remove(Integer id) {
        if (articleService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }


    @ResponseBody
    @PostMapping("/uploadImg")
    R uploadImg(@RequestParam("file") MultipartFile mfImgUrl) {
        String url = "";
        String fileName = mfImgUrl.getOriginalFilename();
        fileName = FileUtil.renameToUUID(fileName);
        String filePath = "";
        filePath = OssUtil.getUploadPrefix(OssUtil.TYPE_ARTICLE_PHOTOS);
        url = filePath + fileName;
        try {
            File file = new File(projectUrlConfig.getUploadPath() + filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileUtil.uploadFile(mfImgUrl.getBytes(), projectUrlConfig.getUploadPath() + filePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("src", imgurl + url);
        map.put("filePath", url);
        map.put("title", fileName);
        return R.ok(0, map);
    }
}
